<template>
  <div
    v-loading="log"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <Card>
      <el-form
        :inline="true"
        :model="page"
        class="demo-form-inline"
        style="display: flex; justify-content: space-around"
      >
        <el-form-item label="账号">
          <el-input v-model="page.user" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            style="width: auto"
            v-model="page.search.createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="组织" style="margin-left: 20px">
          <el-select
            v-model="page.search.orgId"
            filterable
            placeholder="请选择组织"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="margin-left: 20px">
        <Button type="info">搜索</Button>
        <Button style="margin-left: 20px" @click="reset">重置</Button>
        <Dropdown trigger="click" style="margin-left: 20px">
          <Button type="default" href="javascript:void(0)">
            更多
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <template #list>
            <DropdownMenu>
              <DropdownItem @click.native="showModalAdd"
                ><Icon type="md-person-add" /> 新增</DropdownItem
              >
              <DropdownItem
                ><Icon type="md-cloud-download" /> 导入</DropdownItem
              >
              <DropdownItem><Icon type="md-cloud-upload" /> 导出</DropdownItem>
            </DropdownMenu>
          </template>
        </Dropdown>
      </div>
    </Card>

    <el-table :data="tableData" style="width: 100%" max-height="320">
      <el-table-column
        fixed="left"
        prop=""
        label="照片"
        align="center"
        width="150"
      >
        <template slot-scope="scope">
          <el-avatar
            shape="square"
            :size="50"
            :src="scope.row.avatar"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column fixed="left" prop="name" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="account" label="账号" width="120">
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="120">
        <template slot-scope="data">
          <el-tag v-if="data.row.sex == 'M'">男</el-tag>
          <el-tag v-else type="danger">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orgName" label="组织" width="180">
      </el-table-column>
      <el-table-column prop="stationName" label="岗位" width="120">
      </el-table-column>
      <el-table-column
        prop="tag"
        label="状态"
        width="100"
        :filters="[
          { text: '启用', value: '启用' },
          { text: '禁用', value: '禁用' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status == true ? 'success' : 'info'"
            disable-transitions
            >{{ scope.row.status == true ? "启用" : "禁用" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <div>
            <el-link type="primary" @click="editUser(scope.row)"
              ><i class="el-icon-edit"></i> 编辑</el-link
            >
            <el-divider direction="vertical"></el-divider>
            <el-link
              type="primary"
              @click="removeUser(scope.$index, tableData, scope.row.id)"
              ><i class="el-icon-delete"></i> 删除</el-link
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[5, 15, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 新增 -->
    <Modal
      v-model="modalAdd"
      draggable
      sticky
      scrollable
      :mask="false"
      title="新增用户信息"
      :width="700"
    >
      <div style="display: flex">
        <el-upload
          class="avatar-uploader"
          action="/api/auth/pd_auth_user/uploadcontroller"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          name="myfile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <Form
          ref="addUser"
          :model="user"
          :rules="ruleValidate"
          :label-width="80"
        >
          <div style="display: flex">
            <div>
              <FormItem label="姓名" prop="name">
                <Input v-model="user.name" placeholder="姓名"></Input>
              </FormItem>
              <FormItem label="性别">
                <RadioGroup v-model="user.sex">
                  <Radio label="M" border>男</Radio>
                  <Radio label="W" border>女</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem label="组织" prop="orgId">
                <el-select
                  v-model="user.orgId"
                  filterable
                  placeholder="请选择组织"
                >
                  <el-option
                    v-for="item in options1"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </FormItem>
              <FormItem label="手机号" prop="mobile">
                <Input v-model="user.mobile" placeholder="手机号"></Input>
              </FormItem>
            </div>
            <div>
              <FormItem label="账号" prop="account">
                <Input v-model="user.account" placeholder="账户"></Input>
              </FormItem>
              <FormItem label="密码" prop="password">
                <Input v-model="user.password" placeholder="密码"></Input>
              </FormItem>
              <FormItem label="岗位" prop="stationId">
                <el-select
                  v-model="user.stationId"
                  filterable
                  placeholder="请选择岗位"
                >
                  <el-option
                    v-for="item in options2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </FormItem>
              <FormItem label="邮箱" prop="email">
                <Input v-model="user.email" placeholder="邮箱"></Input>
              </FormItem>
            </div>
          </div>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button @click="modalAdd = false">取消</Button>
        <Button type="primary" @click="addUser('addUser')">确认</Button>
      </template>
    </Modal>

    <!-- 编辑 -->
    <Modal
      v-model="modalEdit"
      draggable
      sticky
      scrollable
      :mask="false"
      title="编辑用户信息"
      :width="700"
    >
      <div style="display: flex">
        <el-upload
          class="avatar-uploader"
          action="/api/auth/pd_auth_user/uploadcontroller"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          name="myfile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <Form
          ref="editUser"
          :model="user"
          :rules="ruleValidate"
          :label-width="80"
        >
          <div style="display: flex">
            <div>
              <FormItem label="姓名" prop="name">
                <Input v-model="user.name" placeholder="姓名"></Input>
              </FormItem>
              <FormItem label="性别">
                <RadioGroup v-model="user.sex">
                  <Radio label="M" border>男</Radio>
                  <Radio label="W" border>女</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem label="组织" prop="orgId">
                <el-select
                  v-model="user.orgId"
                  filterable
                  placeholder="请选择组织"
                >
                  <el-option
                    v-for="item in options1"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </FormItem>
            </div>
            <div>
              <FormItem label="手机号" prop="mobile">
                <Input v-model="user.mobile" placeholder="手机号"></Input>
              </FormItem>
              <FormItem label="邮箱" prop="email">
                <Input v-model="user.email" placeholder="邮箱"></Input>
              </FormItem>

              <FormItem label="岗位" prop="stationId">
                <el-select
                  v-model="user.stationId"
                  filterable
                  placeholder="请选择岗位"
                >
                  <el-option
                    v-for="item in options2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </FormItem>
            </div>
          </div>
        </Form>
      </div>
      <!-- 自定义按钮 -->
      <template slot="footer">
        <Button @click="modalEdit = false">取消</Button>
        <Button type="primary" @click="updateUser('editUser')">确认</Button>
      </template>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      log: true,
      tableData: [], //结果集
      page: {
        //分页条件
        pageNum: 1,
        pageSize: 5,
        search: {},
      },
      total: 0, //总数量
      options1: [], //组织
      options2: [], //岗位
      //新增用户信息
      modalAdd: false, //新增模态框
      imageUrl: "", //头像
      user: {
        account: "", //账号
        password: "", //密码
        name: "", //姓名
        orgId: "", //组织ID
        stationId: "", //岗位ID
        email: "", //邮箱
        mobile: "", //手机
        sex: "M", //性别
        status: "1", //状态
        avatar: "", //头像
        createUser: "", //创建人id
        createTime: "", //创建时间
        updateUser: "", //修改用户
        updateTime: "", //修改时间
      },
      //编辑用户信息
      modalEdit: false, //编辑模态框
      ruleValidate: {
        name: [
          {
            required: true,
            message: "请输入用户姓名",
            trigger: "blur",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择组织",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机号",
            trigger: "blur",
          },
        ],
        account: [
          {
            required: true,
            message: "请输入用户账户",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入用户密码",
            trigger: "blur",
          },
        ],
        stationId: [
          {
            required: true,
            message: "请选择岗位",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱",
            trigger: "blur",
          },
        ],
      },
      options: [],
      token: JSON.parse(sessionStorage.getItem("satoken")), //登入用户信息
    };
  },
  created() {
    this.findUser();
    this.findPdCoreOrg();
    this.findCoreStation();
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.user.avatar = res;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.findUser();
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.findUser();
    },
    /**
     * 分页条件查询所有用户
     */
    async findUser() {
      try {
        await fetch("/api/auth/pd_auth_user/findUser", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(this.page),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.code == 11051) {
              this.log = false;
              this.$Message.error(data.msg);
            }
            if (data.code == 200) {
              this.tableData = data.data.list;
              this.total = data.data.total;
              this.log = false;
            }
          });
      } catch (error) {}
    },
    /**
     * 查询所有组织
     */
    async findPdCoreOrg() {
      try {
        await fetch("/api/auth/pd_auth_user/findPdCoreOrg", {
          method: "POST",
        })
          .then((response) => response.json())
          .then((data) => {
            console.log(data);
            // this.options=data.data;
            if (data.code == 200) {
              this.options1 = data.data;
            }
          });
      } catch (error) {}
    },
    /**
     * 查询所有组织
     */
    async findCoreStation() {
      try {
        await fetch("/api/auth/pd_auth_user/findCoreStation", {
          method: "POST",
        })
          .then((response) => response.json())
          .then((data) => {
            console.log(data);
            if (data.code == 200) {
              this.options2 = data.data;
            }
          });
      } catch (error) {}
    },
    /**
     * 重置
     */
    reset() {
      this.page.search = {};
      this.findUser();
    },
    /**
     * 打开新增模态框
     */
    showModalAdd() {
      this.$refs["addUser"].resetFields();
      this.imageUrl = "";
      this.user = {
        account: "", //账号
        password: "", //密码
        name: "", //姓名
        orgId: "", //组织ID
        stationId: "", //岗位ID
        email: "", //邮箱
        mobile: "", //手机
        sex: "M", //性别
        status: "1", //状态
        avatar: "", //头像
        workDescribe: "", //工作描述
        createUser: "", //创建人id
        createTime: "", //创建时间
        updateUser: "", //修改用户
        updateTime: "", //修改时间
      };
      this.modalAdd = true;
    },
    addUser(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          var now = new Date();
          var month = (now.getMonth() + 1).toString().padStart(2, "0");
          var day = now.getDate().toString().padStart(2, "0");
          this.user.createUser = this.token.loginId;
          this.user.createTime =
            now.getFullYear() +
            "-" +
            month +
            "-" +
            day +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();
          console.log(this.user);
          this.axios
            .post("/api/auth/pd_auth_user/addUser", this.user)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.code == 200) {
                this.findUser();
                this.modalAdd = false;
                this.$Message.success("成功新增一条数据!");
              }
            });
        } else {
          this.$Message.error("请填写用户信息");
        }
      });
    },
    /**
     * 删除用户
     * @param {*} id
     */
    removeUser(index, rows, id) {
      this.$confirm("此操作将永久删除该组织, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .post("/api/auth/pd_auth_user/removeUser/" + id)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.data == true) {
                rows.splice(index, 1);
                this.$Message.success("成功删除一条数据");
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * 打开编辑模态框
     * @param {*} data
     */
    editUser(data) {
      this.user = {
        id: 0,
        name: "", //姓名
        orgId: "", //组织ID
        stationId: "", //岗位ID
        email: "", //邮箱
        mobile: "", //手机
        sex: "M", //性别
        status: "1", //状态
        avatar: "", //头像
        updateUser: "", //修改用户
        updateTime: "", //修改时间
      };
      this.$refs["editUser"].resetFields();
      this.user.avatar = data.avatar;
      this.user.id = data.id;
      this.user.name = data.name;
      this.user.mobile = data.mobile;
      this.user.sex = data.sex;
      this.user.email = data.email;
      this.user.orgId = data.orgId;
      this.user.stationId = data.stationId;
      this.imageUrl = data.avatar;
      this.modalEdit = true;
    },
    updateUser(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          var now = new Date();
          var month = (now.getMonth() + 1).toString().padStart(2, "0");
          var day = now.getDate().toString().padStart(2, "0");
          this.user.updateUser = this.token.loginId;
          this.user.updateTime =
            now.getFullYear() +
            "-" +
            month +
            "-" +
            day +
            " " +
            now.getHours() +
            ":" +
            now.getMinutes() +
            ":" +
            now.getSeconds();
          console.log(this.user);
          this.axios
            .post("/api/auth/pd_auth_user/updateUser", this.user)
            .then((r) => {
              if (r.data.code == 11051) {
                this.$Message.error(r.data.msg);
              }
              if (r.data.code == 200) {
                this.findUser();
                this.modalEdit = false;
                this.$Message.success("成功编辑一条数据!");
              }
            });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    filterTag(value, row) {
      return (row.status == true ? "启用" : "禁用") === value;
    },
  },
};
</script>
<style>
.block {
  text-align: center;
  margin-top: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
